//
//  YFCommunicationManager+YFBQHandle.m
//  SquashSpark
//
//  Created by Coollang on 2018/2/9.
//  Copyright © 2018年 Coollang-YF. All rights reserved.
//

#import "YFCommunicationManager+YFBQHandle.h"
#import "YFSwingDetailItem.h"
#import "YFDayRecordItem.h"
#import "YFThreeDItem.h"

@implementation YFCommunicationManager (YFBQHandle)

- (BOOL)isCentralReady {
    BOOL isReady = [LGCentralManager sharedInstance].isCentralReady;
    if (!isReady) {
        UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"Prompt" message:@"Open Bluetooth and allow Squash Spark connection" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alertVc addAction:cancel];
        AppDelegate *appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
        [appdelegate.window.rootViewController presentViewController:alertVc animated:YES completion:nil];
    }
    return isReady;
}

#pragma mark - 发送操作指令
- (void)getDeviceVersionAndBatteryDatawithCompletion:(VersionBlock)block {
    [[YFCommunicationManager shareInstance] requestOperationType:OperationTypeDeviceVersion parmaObject:nil completionBlock:^(BOOL success, id response, NSError *error) {
        NSString *versionT = nil;
        NSInteger batteryT = -1;
        if (response != nil) {
            NSDictionary *dict = response[@"bleDesc"];
            if([dict.allKeys containsObject:@"version"]){
                versionT = dict[@"version"];
            }
            if([dict.allKeys containsObject:@"battery"]){
                batteryT = [dict[@"battery"] integerValue];
            }
        }
        if (block) {
            block(success,versionT,batteryT);
        }
    }];
}

- (void)setDeviceHandType:(HandDirectionType)handType completion:(HandDataBlock)block {
    [[YFCommunicationManager shareInstance] requestOperationType:OperationTypeHand parmaObject:@(handType) completionBlock:^(BOOL success, id response, NSError *error) {
        NSString *handT = nil;
        if (response != nil) {
            NSDictionary *dict = response[@"bleDesc"];
            if([dict.allKeys containsObject:@"hand"]){
                handT = dict[@"hand"];
            }
        }
        if (block) {
            block(success,handT);
        }
    }];
}

- (void)enterRealTimeModel:(BleCompletionBlock)enterStateBlock realTimeDataCallBlock:(RunTimeDataBlock)block {
    [[YFCommunicationManager shareInstance] requestOperationType:OperationTypeEnterRunTimeData parmaObject:nil completionBlock:^(BOOL success, id response, NSError *error) {
        if (success && response != nil) {
            id result = response[@"bleDesc"];
            if ([result isKindOfClass:[NSDictionary class]]) {
                NSDictionary *dict = result;
                SportPoseType actionType = [[self checkDict:dict key:@"actionType"] integerValue];
                NSInteger speed = [[self checkDict:dict key:@"swingSpeed"] integerValue];
                float strength = [[self checkDict:dict key:@"strength"] floatValue];
                BOOL isHitball = [[self checkDict:dict key:@"isHitball"] boolValue];
                NSInteger swingTime = [[self checkDict:dict key:@"swingTime"] integerValue];
                NSInteger hitBallTime = [[self checkDict:dict key:@"hitBallTime"] integerValue];
                NSInteger areaValue = [[self checkDict:dict key:@"areaValue"] integerValue];
                HandDirectionType handType = [[self checkDict:dict key:@"handType"] integerValue];
                ServeDirectionType serveDirectionType = [[self checkDict:dict key:@"serveDirectionType"] integerValue];
                JCHandBallType handBallType = [[self checkDict:dict key:@"handBallType"] integerValue];
                NSTimeInterval timeStamp = [[self checkDict:dict key:@"timeStamp"] longLongValue];
                
                if (block) {
                    block(YES,actionType,speed,strength,swingTime,hitBallTime,isHitball,areaValue,handType,serveDirectionType,handBallType,timeStamp);
                }
            }else {
                if (enterStateBlock) {
                    enterStateBlock(YES,nil);
                }
            }
        }else {
            if (enterStateBlock) {
                enterStateBlock(NO,error);
            }
        }
    }];
}
- (void)quitRealTimeModelCompleted:(void(^)(BOOL success))completed {
    [[YFCommunicationManager shareInstance] requestOperationType:OperationTypeQuitRunTime parmaObject:nil completionBlock:^(BOOL success, id response, NSError *error) {
        if (completed) {
            completed(success);
        }
    }];
}

// 获取主页面数据
- (void)getHomePageDataWithCallBlock:(HomePageDataBlock)block {
    [[YFCommunicationManager shareInstance] requestOperationType:OperationTypeReadHomePageData parmaObject:nil completionBlock:^(BOOL success, id response, NSError *error) {
        NSLog(@"HomePage:%@",response);
        if (success && response != nil && [response[@"bleDesc"] isKindOfClass:[NSArray class]]) {
            NSMutableArray *arrM = [NSMutableArray array];
            for (id dict in response[@"bleDesc"]) {
                YFDayRecordItem *dayRecordItem = [[YFDayRecordItem alloc] init];
                //YFDayRecordItem *dayRecordItem = [[YFDayRecordItem alloc] initWithFormDeviceDict:dict];
                [dayRecordItem dayRecordItemFormDeviceDict:dict];
                [arrM addObject:dayRecordItem];
            }
            block(arrM.copy,nil);
        }else {
            if (block) {
                block(nil,error);
            }
        }
    }];
}


// 获取详情数据
- (void)getSwingDetailItemWithDay:(NSTimeInterval)dayUnixTimeStamp indexJ:(NSUInteger)indexJ CallBlock:(SwingDetailItemBlock)swingDetailBlock readCompleted:(void(^)(BOOL success))completed {
    if (dayUnixTimeStamp <= 0) {
        if (completed) {
            completed(NO);
        }
        return;
    }
    NSDictionary *parame = @{
                             @"SwingDetail.DayUnixTimeStamp":@(dayUnixTimeStamp),
                             @"SwingDetail.Index":@(indexJ),
                             };
    [[YFCommunicationManager shareInstance] requestOperationType:OperationTypeReadSwingDetailData parmaObject:parame completionBlock:^(BOOL success, id response, NSError *error) {
        NSLog(@"SwingDetail:%@",response);
        if (success && response != nil) {
            if ([response[@"bleDesc"] isKindOfClass:[NSDictionary class]] && swingDetailBlock) {
                YFSwingDetailItem *swingItem = [[YFSwingDetailItem alloc] init];
                [swingItem swingDetailItemFormDeviceDict:response[@"bleDesc"]];
                swingDetailBlock(swingItem,nil);
            }else {
                if (completed) {
                    completed(YES);
                }
            }
        }else {
            if (swingDetailBlock) {
                swingDetailBlock(nil,error);
            }
        }
    }];
}

- (void)enter3DModel:(BleCompletionBlock)enterStateBlock swing3DDataCallBlock:(ThreeDItemBlock)threeDItemBlock {
    
    __block YFThreeDItem *threeDItem;
    [[YFCommunicationManager shareInstance] requestOperationType:OperationType3DData parmaObject:nil completionBlock:^(BOOL success, id response, NSError *error) {
        if (success && response != nil) {
            NSDictionary *dict = response;
            if ([dict[@"code"] isEqualToString:@"0"]) {
                if (enterStateBlock) {
                    enterStateBlock(YES,nil);
                }
                // 初始化模型
                threeDItem = [[YFThreeDItem alloc] init];
            }else{
                if ([dict[@"code"] isEqualToString:@"1"]){
                    [threeDItem parseThreeDItemFormDeviceDict:dict[@"bleDesc"]];
                }else if ([dict[@"code"] isEqualToString:@"2"]){
                    YFThreeDDetailItem *detilItem = [[YFThreeDDetailItem alloc] init];
                    [detilItem parseThreeDDetailItemFormDeviceDict:dict[@"bleDesc"]];
                    [threeDItem.threeDDetailItems addObject:detilItem];
                    
                }else {
                    // 向硬件发送3D数据接收完成指令
                    [[YFCommunicationManager shareInstance] requestOperationType:OperationType3DData parmaObject:@(4) completionBlock:^(BOOL success, id response, NSError *error) {
                        NSLog(@"%d",success);
                    }];
                    // 处理数据
                    [threeDItem disposeForeBackFaceOfRacket:(NSArray *)threeDItem.threeDDetailItems];
                    // 读取完成
                    if (threeDItemBlock) {
                        threeDItemBlock(threeDItem,nil);
                    }
                    // 重新再创建一个
                    threeDItem = [[YFThreeDItem alloc] init];
                }
            }
        }else {
            if (threeDItemBlock) {
                threeDItemBlock(nil,error);
            }
        }
    }];
}

- (id)checkDict:(NSDictionary *)dict key:(NSString *)key {
    if([dict.allKeys containsObject:key]){
        return dict[key];
    }
    return @"";
}
@end
